﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net;
using System.Web.Security;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Baidu.Aip.Speech;
using Baidu.Aip.Demo;
namespace WinFormStudy
{
    public partial class Form_Translate : Form
    {
        public Form_Translate()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            string appid="20171011000087472";
            string seck="6Si5De0agcy8_WY6uwuG";
            SpeechDemo speech = new SpeechDemo();
            string word = tbWord.Text;
            Random r=new Random();
            int salt = r.Next(0, 1000);
            string sign = Md5(appid + word + salt + seck);
            word = System.Web.HttpUtility.UrlEncode(word, System.Text.Encoding.UTF8);

            /*
            auto 自动检测,zh中文,en	英语,yue粤语,wyw文言文,jp日语, kor韩语,fra法语,
            spa西班牙语,th泰语,ara阿拉伯语,ru俄语,pt葡萄牙语,de德语,it意大利语,
            el希腊语, nl荷兰语,pl波兰语,bul保加利亚语,est爱沙尼亚语,dan丹麦语,
            fin芬兰语,cs捷克语,rom	罗马尼亚语,slo斯洛文尼亚语,swe瑞典语,
            hu匈牙利语,cht繁体中文,vie越南语*/
            string url = "http://fanyi-api.baidu.com/api/trans/vip/translate?q=" + word + "&from=zh&to=en&appid="+appid+"&salt=" + salt + "&sign="+sign;
            WebClient MyWebClient = new WebClient();
            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
            try
            {
                Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
                string pageHtml = Encoding.UTF8.GetString(pageData);
                JObject json = (JObject)JsonConvert.DeserializeObject(pageHtml);
                JArray jar = JArray.Parse(json["trans_result"].ToString());
                string result = JObject.Parse(jar[0].ToString())["dst"].ToString();
                tbResult.Text = result;
                //speech.Tts(result);
            }
            catch
            { 
                
            }
           
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Md5(string str)
        {
            string cl = str;
            string pwd = "";
            MD5 md5 = MD5.Create();//实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("x2");
            }
            return pwd;
        }


    }
}
